<?php
namespace common\components\extenders;

use yii\base\Component;
use yii\console\Exception;
use yii\helpers\Json;

class SwooleClientManage extends Component
{

    public $hostname = '114.215.138.1';
    public $port = 9501;
    public $connectionTimeout =1;
    public $udp_connect =0;//为1代表设置为非阻塞socket，connect会立即返回，如果将$flag设置为1，那么在send/recv前必须使用swoole_client_select来检测是否完成了连接；
    //现在是个0说明是阻塞的
    private $_socket;//连接状态


//    public function connection(){
//        if ($this->_socket !== null) {
//            return;
//        }
//        $this->_socket = new \swoole_client(SWOOLE_SOCK_TCP);//新建客户端
//        if (!$this->_socket->connect($this->hostname, $this->port,$this->connectionTimeout,$this->udp_connect))//连接到远程服务器
//        {
//            \Yii::error("connect failed. Error: {$this->_socket->errCode}\n", __CLASS__);
//        }
//    }

//    public function send($data){
//        $this->connection();
//        $socket = new \swoole_client(SWOOLE_SOCK_TCP);//新建客户端
//        $socket->connect($this->hostname, $this->port,$this->connectionTimeout,$this->udp_connect);
//        $data=Json::encode($data);
//        $socket->send($data);
//        $socket->close();
//    }

    public function send($data){
        $this->port = \Yii::$app->params['swooleTaskPort'];
        $socket = new \swoole_client(SWOOLE_SOCK_TCP);//新建客户端，支持在php-fpm/apache中创建一个TCP长连接到服务器端 SWOOLE_SOCK_TCP | SWOOLE_KEEP 好像有bug别用
        try{
            $connect_res = $socket->connect($this->hostname, $this->port,$this->connectionTimeout,$this->udp_connect);
            if(!$connect_res){
                \Yii::error($connect_res);
                \Yii::error(socket_strerror($socket->errCode));
            }
        }catch (Exception $e){
            \Yii::error('swooleclient connect failed');
            \Yii::error($e->getMessage());
            \Yii::error(socket_strerror($socket->errCode));
        }
        $data=Json::encode($data);
        try{
            $send_result = $socket->send($data);//文档说send完不要立即close，是不安全的，无论是服务器端还是客户端
            //send只是将数据放到了socket缓存区，究竟操作系统有没有发送成功，服务器有没有收到货处理都没法确切保证
            //但是怎么做文档也没说只是给了个close关闭后的处理
            if(!$send_result){
                \Yii::error($send_result);
                \Yii::error(socket_strerror($socket->errCode));
            }
            $socket->close();
        }catch (Exception $e){
            \Yii::error('swooleclient send data failed.');
            \Yii::error($e->getMessage());
        }

    }


}